import axios, { AxiosRequestConfig } from 'axios'
import type { AxiosInstance } from 'axios'
import type { TAxiosInterceptors, TAxiosConfig } from './type'
import { ElLoading } from 'element-plus'
import type { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type'

const DEFAULT_LOADING = false
class TAxios {
  instance: AxiosInstance
  interceptorHooks?: TAxiosInterceptors
  loading?: ILoadingInstance
  showLoading: boolean
  constructor(config: TAxiosConfig) {
    this.instance = axios.create(config)
    this.interceptorHooks = config.interceptorHooks
    this.showLoading = config.showLoading ?? DEFAULT_LOADING

    // 单个实例对象的拦截器
    this.instance.interceptors.request.use(
      this.interceptorHooks?.requestInterceptor,
      this.interceptorHooks?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptorHooks?.responseInterceptor,
      this.interceptorHooks?.responseInterceptorCatch
    )
    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading === true) {
          this.loading = ElLoading.service({
            lock: true,
            text: '🚀正在攻克服务器....',
            background: 'rgba(0,0,0,0.5)'
          })
        }
        return config
      },
      (err) => {
        this.loading?.close()
        return err
      }
    ),
      this.instance.interceptors.response.use(
        (res) => {
          this.loading?.close()
          const data = res.data
          return data
        },
        (err) => {
          this.loading?.close()
          return err
        }
      )
  }
  request<T>(config: TAxiosConfig): Promise<T> {
    0
    return new Promise((resolve, reject) => {
      if (config.interceptorHooks?.requestInterceptor) {
        config = config.interceptorHooks.requestInterceptor(config)
      }
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptorHooks?.responseInterceptor) {
            res = config.interceptorHooks.responseInterceptor(res)
          }
          this.showLoading = DEFAULT_LOADING
          resolve(res)
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING
          reject(err)
          return err
        })
    })
  }
  get<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }

  post<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default TAxios
